var Manager=require("../Manager")
module.exports={
    _state:0,
    /**
     * 收到key请求
     * GET / HTTP/1.1
     * Host: 192.168.1.99:8010
     * Connection: Upgrade
     * Pragma: no-cache
     * Cache-Control: no-cache
     * Upgrade: websocket
     * Origin: http://127.0.0.1
     * Sec-WebSocket-Version: 13
     * User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36
     * Accept-Encoding: gzip, deflate, sdch
     * Accept-Language: zh-CN,zh;q=0.8
     * Sec-WebSocket-Key: Wtj+WuQpUNFcuOwKlQXStA==
     * Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
     */
    recieveKey:function(msg)
    {
        var returnMsg="HTTP/1.1 101 Switching Protocols\n"+
            "Upgrade:websocket\n"+
            "Connection:Upgrade\n"+
            "Sec-WebSocket-Accept:";

        var keyHead="Sec-WebSocket-Key: ";
        var arr=msg.split("\r\n");
        var index=-1;
        var key="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
        for(var i=0;i<arr.length;i++)
        {
            var tem=arr[i];
            index=tem.indexOf(keyHead);
            if(index!=-1)
            {
                key=tem.substring(index+keyHead.length)+key;
                break;
            }
        }
        var tem2=SHA1.hashToBase64(key);
        returnMsg+=tem2+"\n\n";

        var bytes=new ByteArray();
        bytes.endian=Endian.LITTLE_ENDIAN;

        bytes.writeUTFBytes(returnMsg);
        Manager.communicationManager.serverSocketModule.sendData(_name,_id,bytes);
        this._state=2;
    },
    /**
     * 协议处理
     * */
    recieveData:function(bytes)
    {
        var data=this.upPack(bytes)[0];
        if(data.data)
            Manager.communicationManager.serverSocketModule["notify"](CommunicationCommand.SERVER_SOCKET_CLIENT_DATA,{name:"dataServer",ip:_ip,port:_port,id:_id,data:data.data});
        else if(typeof(data.data)=="string")
            Manager.communicationManager.serverSocketModule["notify"](CommunicationCommand.SERVER_SOCKET_CLIENT_DATA,{name:"dataServer",ip:_ip,port:_port,id:_id,data:JsonTransToBin.transStringToBin(data.data)});
        else
            debug("意外的协议格式"+data.data,"WebSocketClient");
    },
    packageData:function(ba)
    {
        return ba;
    },
    unpackData:function()
    {
        if(_cacheBytes.length<1)
            return null;
        var tem=_cacheBytes;
        _cacheBytes=new ByteArray();
        _cacheBytes.endian=tem.endian;
        return tem;
    }
}